﻿using System.Collections.ObjectModel;
using System.Net.Http;
using System.Text.Json;
using MeterReader.WPF.Common.Extensions;
using MeterReader.WPF.Models;

namespace MeterReader.WPF.Services
{
    public class DataService : IDataService
    {
        private readonly HttpClient? _httpClient;
        private CancellationTokenSource _cancellationTokenSource = new();
        private readonly ObservableCollection<MeterDataCollection> _collection = new();
        private int _num = 0;
        private bool _isWorking = false;

        public bool IsWorking => _isWorking;

        public event EventHandler? WorkStatusChanged;

        public ObservableCollection<MeterDataCollection> GetMeterDataCollections() => _collection;

        public async void StartPeriodicRead()
        {
            OnWorkStatusChanged(true);
            await Task.Delay(1);
            try
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    // 读取数据
                    await GetTMeterAsync().WaitAsync(TimeSpan.FromSeconds(2));
                    // 等待 1 秒钟
                    await Task.Delay(1000, _cancellationTokenSource.Token);
                    // 写入数据库 ,发送http
                }
            }
            catch (OperationCanceledException ex)
            {
                StopPeriodicRead();
                //_logger?.LogInformation($"停止读取数据：{ex.Message}");
            }
            catch (TimeoutException ex)
            {
                StopPeriodicRead();
                string message = $"读取数据超时：{this.GetType().FullName}：{ex.Message}{Environment.NewLine}Inner Exception: {ex.InnerException?.Message}";
                //_logger!.LogError(message);
                //_eventAggregator.GetEvent<WorkStatusChangedEvent>().Publish(new() { Message = message, Token = "Exception" });
            }
            catch (Exception ex)
            {
                StopPeriodicRead();
                string message = $"读取数据异常：{this.GetType().FullName}：{ex.Message}{Environment.NewLine}Inner Exception: {ex.InnerException?.Message}";
                //_logger!.LogError(message);
                //_eventAggregator.GetEvent<WorkStatusChangedEvent>().Publish(new() { Message = message, Token = "Exception" });
            }
        }

        public void StopPeriodicRead()
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource = new CancellationTokenSource();
            OnWorkStatusChanged(false);
        }

        /// <summary>
        /// 向 Webapi 发送 get 请求，读取数据
        /// </summary>
        /// <returns>获取数据模型</returns>
        private async Task<TMeter> GetTMeterAsync()
        {
            string api = "https://localhost:7121/Values/GetValues";
            string url = string.Format("{0}{1}{2}", api, "?Num=", _num);

            using (HttpClient client = new())
            {
                var response = await client.GetAsync(url).WaitAsync(TimeSpan.FromSeconds(2));
                var json = await response.Content.ReadAsStringAsync();
                var meter = JsonSerializer.Deserialize<TMeter>(json);
                if (meter!.Id != 0)
                {
                    _collection.AddNewMeterDataCollection(meter);
                }
                _num++;
                return meter!;
            }
        }
        /// <summary>
        /// 属性改变
        /// </summary>
        /// <param name="status"></param>
        protected virtual void OnWorkStatusChanged(bool status)
        {
            _isWorking = status;
            WorkStatusChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}
